package cn.org.atool.generator.javafile.template;

import cn.org.atool.fluent.mybatis.metadata.DbType;
import cn.org.atool.generator.database.config.impl.RelationConfig;
import cn.org.atool.generator.database.model.ConfigKey;
import cn.org.atool.generator.database.model.TableField;
import cn.org.atool.generator.database.model.TableSetter;
import com.squareup.javapoet.*;

import javax.lang.model.element.Modifier;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

import static cn.org.atool.generator.database.model.Naming.capitalFirst;
import static cn.org.atool.generator.util.ClassNames.*;
import static cn.org.atool.generator.util.GeneratorHelper.isBlank;

/**
 * Entity代码生成构造
 *
 * @author wudarui
 */
@SuppressWarnings("rawtypes")
public class PojoFile extends AbstractTemplateFile {

    public PojoFile(TableSetter table) {
        super(table);
        this.packageName = entityPackage(table);
        this.klassName = entityClass(table);
    }

    public static TypeName entityName(TableSetter table) {
        return ClassName.get(entityPackage(table), entityClass(table));
    }

    public static String entityPackage(TableSetter table) {
        return table.gc().getBasePackage() + ".entity.pojo";
    }

    /**
     * 返回Entity类名
     *
     * @param table TableSetter
     * @return ignore
     */
    public static String entityClass(TableSetter table) {
        String entityPrefix = table.getEntityPrefix();
        if (entityPrefix.endsWith("PoJo")) {
            return entityPrefix;
        } else {
            return entityPrefix + "PoJo";
        }
    }

    @Override
    protected void build(TypeSpec.Builder spec) {
        spec.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class)
            .addMember("value", "{$S, $S}", "rawtypes", "unchecked")
            .build());
        this.lombok(spec).addJavadoc("简易版的数据库实体");
        /**
         * addJavadoc
         * $L : 占位符
         * $T 引用实体类名称
         */

        spec.addSuperinterface(ClassName.get("java.io","Serializable"));

        spec.addField(FieldSpec.builder(long.class, "serialVersionUID",
                Modifier.STATIC, Modifier.FINAL, Modifier.PRIVATE)
            .initializer("1L")
            .build());

        for (TableField field : table.getFields()) {
            FieldSpec.Builder fb = FieldSpec.builder(field.getJavaType(), field.getName(), Modifier.PRIVATE);

            //字段注释
            fb.addJavadoc("$L", field.getComment());

            spec.addField(fb.build());
            if (!table.gc().isLombok()) {
                String capital = capitalFirst(field.getName());
                spec.addMethod(this.m_getter(capital, field));
                spec.addMethod(this.m_setter(capital, field, table.gc().isSetterChain()));
            }
        }

    }

    /**
     * 设置 lombok 相关注解
     *
     * @param spec TypeSpec.Builder
     */
    private TypeSpec.Builder lombok(TypeSpec.Builder spec) {
        if (!table.gc().isLombok()) {
            return spec;
        }
        spec.addAnnotation(Lombok_Data);
        spec
            .addAnnotation(Lombok_AllArgsConstructor)
            .addAnnotation(Lombok_NoArgsConstructor);
        return spec;
    }

    private MethodSpec m_getter(String capital, TableField field) {
        return MethodSpec.methodBuilder("get" + capital)
            .addModifiers(Modifier.PUBLIC)
            .returns(field.getJavaType())
            .addStatement("return this.$L", field.getName())
            .build();
    }

    private MethodSpec m_setter(String capital, TableField field, boolean setterChain) {
        MethodSpec.Builder spec = MethodSpec.methodBuilder("set" + capital)
            .addModifiers(Modifier.PUBLIC);
        if (setterChain) {
            spec.returns(this.className());
        }
        spec.addParameter(field.getJavaType(), field.getName())
            .addStatement("this.$L = $L", field.getName(), field.getName());
        if (setterChain) {
            spec.addStatement("return this");
        }
        return spec.build();
    }


    /**
     * 泛型参数只有一个，且可以设置为Entity对象
     *
     * @param interfaceName 接口名称
     * @param typeVariables 接口泛型参数列表
     * @return ignore
     */
    private boolean hasEntityType(String interfaceName, TypeVariable[] typeVariables) {
        if (typeVariables.length != 1) {
            return false;
        }
        for (Type bound : typeVariables[0].getBounds()) {
            String tn = bound.getTypeName();
            if (Objects.equals(tn, interfaceName) || Allow_Entity_Bounds.contains(tn)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Entity自定义接口的泛型如果是下列类型子类型，可以使用Entity作为泛型参数
     */
    private static final Set<String> Allow_Entity_Bounds = new HashSet<>();

    static {
        Allow_Entity_Bounds.add("cn.org.atool.fluent.mybatis.base.IEntity");
        Allow_Entity_Bounds.add(Object.class.getName());
        Allow_Entity_Bounds.add(Serializable.class.getName());
    }


    private String notNewLine(String text) {
        if (text == null) {
            return "";
        } else {
            return text.replaceAll("[\\n\\r]+", ";").trim();
        }
    }

    @Override
    protected boolean isInterface() {
        return false;
    }
}